<?php
class kcValidatorImage extends sfValidatorFile
{
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);
    
    $this->addMessage('upload_corrupt'  , 'El archivo esta corrupto o tiene una extension incorecta . Pr favor revise el archivo y levantelo de nuevo');
    $this->addMessage('too-big-image'   , 'Imagen muy grande (ancho x alto');
  }
  
  protected function doClean($value)
  {
    if (!is_array($value) || !isset($value['tmp_name']))
    {
      throw new sfValidatorError($this, 'invalid', array('value' => (string) $value));
    }

    if (!isset($value['name']))
    {
      $value['name'] = '';
    }

    if (!isset($value['error']))
    {
      $value['error'] = UPLOAD_ERR_OK;
    }

    if (!isset($value['size']))
    {
      $value['size'] = filesize($value['tmp_name']);
    }

    if (!isset($value['type']))
    {
      $value['type'] = 'application/octet-stream';
    }

    switch ($value['error'])
    {
      case UPLOAD_ERR_INI_SIZE:
        throw new sfValidatorError($this, 'max_size', array('max_size' => ini_get('upload_max_filesize'), 'size' => (int) $value['size']));
      case UPLOAD_ERR_FORM_SIZE:
        throw new sfValidatorError($this, 'max_size', array('max_size' => 0, 'size' => (int) $value['size']));
      case UPLOAD_ERR_PARTIAL:
        throw new sfValidatorError($this, 'partial');
      case UPLOAD_ERR_NO_TMP_DIR:
        throw new sfValidatorError($this, 'no_tmp_dir');
      case UPLOAD_ERR_CANT_WRITE:
        throw new sfValidatorError($this, 'no_cant_write');
      case UPLOAD_ERR_EXTENSION:
        throw new sfValidatorError($this, 'extension');
    }

    // check file size
    if ($this->hasOption('max_size') && $this->getOption('max_size') < (int) $value['size'])
    {
      throw new sfValidatorError($this, 'max_size', array('max_size' => $this->getOption('max_size'), 'size' => (int) $value['size']));
    }

    $mimeType = $this->getMimeType((string) $value['tmp_name'], (string) $value['type']);

    // check mime type
    if ($this->hasOption('mime_types'))
    {
      $mimeTypes = is_array($this->getOption('mime_types')) ? $this->getOption('mime_types') : $this->getMimeTypesFromCategory($this->getOption('mime_types'));
      if (!in_array($mimeType, $mimeTypes))
      {
        throw new sfValidatorError($this, 'mime_types', array('mime_types' => $mimeTypes, 'mime_type' => $mimeType));
      }
    }
    
    // check mime correponde to extension
    list($partname, $ext) = ToolkitFile::splitExtensions($value['name']);
    $rawExtension         = $ext[count($ext) - 1];
    $verified             = $this->verify($value['tmp_name'], $rawExtension);
    
    // validate size for Memmory
    $this->validateSize($value, $mimeType);

    $class = $this->getOption('validated_file_class');

    return new $class($value['name'], $mimeType, $value['tmp_name'], $value['size'], $this->getOption('path'));
  }
  
  protected function validateSize($value, $mimeType)
  {
    if (in_array($mimeType, MediaConfiguration::getImageMimeTypeList()))
    {
      $handler = MediaHandler::getHandler($mimeType);
      if ($handler)
      {
        $gis    = $handler->getImageSize($value['tmp_name']);
        $width  = $gis[0];
        $height = $gis[1];
        if ($mimeType !== 'image/jpeg' && $width * $height > MediaConfiguration::MAX_IMAGE_AREA)
		{
		  throw new sfValidatorError($this, 'too-big-image', array());
		}
      }
    }
  }
  
  protected function verify($tmpfile, $extension)
  {
    # magically determine mime type
    $mimeMagic = MimeMagic::singleton();
    $mime      = $mimeMagic->guessMimeType($tmpfile, false);

    # check mime type, if desired
    if (MediaConfiguration::VERIFY_MIME_TYPE)
    {
      #check mime type against file extension
      if(!$this->verifyExtension($mime, $extension))
      {
      	throw new sfValidatorError($this, 'upload_corrupt', array());
      }
    }
  }
  
  protected function verifyExtension($mime, $extension)
  {
    $mimeMagic = MimeMagic::singleton();

    if (!$mime || $mime == 'unknown' || $mime == 'unknown/unknown')
    {
      return (!$mimeMagic->isRecognizableExtension($extension)) ? true : false;
    }

    $match = $mimeMagic->isMatchingExtension($extension, $mime);
    
    return ($match === NULL) ? true : ($match === true) ? true : false;
  }
  
  protected function getRequest()
  {
  	return sfContext::getInstance()->getRequest();
  }
}
